<?php
/**
 * Cart page controller
 *
 * @author Valery
 *
 */

class CategoryController extends modules_default_controllers_ControllerBase
{
	protected $_bForLoggedUsersOnly = false;
	protected $_contentLayout = 'contentonly';

//----------------------------------------------------------------------------------------------------

	public function init()
	{
		if (! $this->getRequest()->isXmlHttpRequest())
		{
			$this->view->title = 'Category';
			parent::init();
		}

		$this->_helper->AjaxContext()->initContext('json');
	}

//----------------------------------------------------------------------------------------------------

	public function indexAction()
	{
		$idCategory 			= $this->_getParam('category', 0);
		$page 					= $this->_getParam('page', 1);
		$idCard					= (int)$this->_getParam('card', 0);
		$category 				= models_CardcategoryMapper::findById($idCategory);

		if (null == $category)
		{
			throw new Zend_Controller_Action_Exception('This page dont exist', 404);
		}

		$cards 					= models_CardMapper::findByCategoryId($idCategory, $page);

		if (0 != $idCard)
		{
			$card = models_CardMapper::findById($idCard);
			if (null == $card || $card->cardCategoryId != $idCategory)
			{
				throw new Zend_Controller_Action_Exception('This page dont exist', 404);
			}
			$newPage = $page;
			$result = false;
			do
			{
				foreach ($cards['array'] as $item)
				{
					if ($item->id == $idCard)
					{
						$result = true;
					}
				}
				if (!$result)
				{
					$newPage++;

					if ($newPage > $cards['paginator']->count())
					{
						$newPage = 1;
					}
					$cards		= models_CardMapper::findByCategoryId($idCategory, $newPage);
				}
			} while (!$result && $newPage != $page);
			if ($newPage != $page)
			{
				$this->_redirect('/category/' . $idCategory . '/page/' . $newPage . '/card/' . (int)$idCard);
			}
		}

		$allFavoriteCategory	= models_FavoritecategoryMapper::getAll();

		$this->view->allFavoriteCategory	= $allFavoriteCategory['array'];
		$this->view->category 				= $category;
		$this->view->cards 					= $cards['paginator'];
		if ($idCard)
		{
			$this->view->activeCard			= $idCard;
		}
	}

//----------------------------------------------------------------------------------------------------

}
